const http = require('../../../utils/request')
const { taskApi } = require('../../../utils/api')

Page({
  data: {
    task: null,
    taskId: null,
    pageType: null
  },

  onLoad(options) {
    const { id } = options
    this.setData({ 
      taskId: id
    })
    this.getTaskDetail()
  },

  // 获取工单详情
  getTaskDetail() {
    const params = {
      taskCode: this.data.taskId
    }
    return http.get(taskApi.search(params))
      .then(res => {
        // 由于search接口返回的是分页数据，我们需要取第一条记录
        const taskDetail = res.currentPageRecords?.[0]
        if (!taskDetail) {
          throw new Error('工单不存在')
        }
        
        this.setData({
          task: {
            ...taskDetail,
            createTime: this.formatTime(taskDetail.createTime),
            address: taskDetail.addr
          }
        })
      })
      .catch(err => {
        wx.showToast({
          title: err.message || '获取工单详情失败',
          icon: 'none'
        })
        return Promise.reject(err)
      })
  },

  // 格式化时间
  formatTime(timestamp) {
    if(!timestamp) return ''
    const date = new Date(timestamp)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hour = date.getHours().toString().padStart(2, '0')
    const minute = date.getMinutes().toString().padStart(2, '0')
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  // 接受工单
  onAccept() {
    const { task } = this.data
    http.get(taskApi.acceptTask(task.taskId))
      .then(() => {
        wx.showToast({
          title: '接受工单成功',
          icon: 'success',
          duration: 1500,
          success: () => {
            // 更新上一页数据
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if(prevPage) {
              // 从待办工单中移除该工单
              const pendingTasks = prevPage.data.pendingTasks.filter(task => task.taskCode !== this.data.taskId)
              prevPage.setData({ pendingTasks })
            }
            
            setTimeout(() => {
              // 返回上一页并切换到进行中工单tab
              wx.navigateBack({
                success: () => {
                  wx.switchTab({
                    url: '/pages/task/ongoing/index'
                  })
                }
              })
            }, 1500)
          }
        })
      })
      .catch(err => {
        wx.showToast({
          title: err || '接受工单失败',
          icon: 'none'
        })
      })
  },

  // 拒绝工单
  onReject() {
    wx.showModal({
      title: '提示',
      content: '确定要拒绝该工单吗？',
      success: (res) => {
        if(res.confirm) {
          const { task } = this.data
          http.post(taskApi.cancelTask(task.taskId), {
            reason: '维修员拒绝'
          })
            .then(() => {
              wx.showToast({
                title: '已拒绝工单',
                icon: 'success',
                duration: 1500,
                success: () => {
                  // 更新上一页数据
                  const pages = getCurrentPages()
                  const prevPage = pages[pages.length - 2]
                  if(prevPage) {
                    // 从待办工单中移除该工单
                    const pendingTasks = prevPage.data.pendingTasks.filter(task => task.taskCode !== this.data.taskId)
                    prevPage.setData({ pendingTasks })
                  }
                  
                  setTimeout(() => {
                    // 返回上一页并切换到全部工单tab
                    wx.navigateBack({
                      success: () => {
                        wx.switchTab({
                          url: '/pages/task/all/index'
                        })
                      }
                    })
                  }, 1500)
                }
              })
            })
            .catch(err => {
              wx.showToast({
                title: err || '拒绝工单失败',
                icon: 'none'
              })
            })
        }
      }
    })
  },

  // 取消工单
  onCancel() {
    wx.showModal({
      title: '提示',
      content: '确定要取消该工单吗？',
      success: (res) => {
        if(res.confirm) {
          const { task } = this.data
          http.post(taskApi.cancelTask(task.taskId), {
            reason: '维修员取消'
          })
            .then(() => {
              wx.showToast({
                title: '已取消工单',
                icon: 'success',
                duration: 1500,
                success: () => {
                  // 更新上一页数据
                  const pages = getCurrentPages()
                  const prevPage = pages[pages.length - 2]
                  if(prevPage) {
                    // 从进行中工单中移除该工单
                    const tasks = prevPage.data.tasks.filter(task => task.taskCode !== this.data.taskId)
                    prevPage.setData({ tasks })
                  }
                  
                  setTimeout(() => {
                    // 返回上一页并切换到全部工单tab
                    wx.navigateBack({
                      success: () => {
                        wx.switchTab({
                          url: '/pages/task/all/index'
                        })
                      }
                    })
                  }, 1500)
                }
              })
            })
            .catch(err => {
              wx.showToast({
                title: err || '取消工单失败',
                icon: 'none'
              })
            })
        }
      }
    })
  },

  // 完成工单
  onComplete() {
    wx.showModal({
      title: '提示',
      content: '确定要完成该工单吗？',
      success: (res) => {
        if(res.confirm) {
          const { task } = this.data
          http.get(taskApi.completeTask(task.taskId))
            .then(() => {
              wx.showToast({
                title: '工单已完成',
                icon: 'success',
                duration: 1500,
                success: () => {
                  // 更新上一页数据
                  const pages = getCurrentPages()
                  const prevPage = pages[pages.length - 2]
                  if(prevPage) {
                    // 从进行中工单中移除该工单
                    const tasks = prevPage.data.tasks.filter(task => task.taskCode !== this.data.taskId)
                    prevPage.setData({ tasks })
                  }
                  
                  setTimeout(() => {
                    // 返回上一页并切换到全部工单tab
                    wx.navigateBack({
                      success: () => {
                        wx.switchTab({
                          url: '/pages/task/all/index'
                        })
                      }
                    })
                  }, 1500)
                }
              })
            })
            .catch(err => {
              wx.showToast({
                title: err || '完成工单失败',
                icon: 'none'
              })
            })
        }
      }
    })
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.getTaskDetail()
      .then(() => {
        wx.stopPullDownRefresh()
      })
  }
}) 